package gameengine;

import filemanager.FileMgr;

public class HiScoreMgr {

	private int[] scores;
	private String[] names;
	private String scoreFile;
	
	public HiScoreMgr(){
		scores = new int[10];
		names = new String[10];
		retrieveScores();
	}
	
	public int[] getScores() {
		return scores;
	}

	public String[] getNames() {
		return names;
	}

	public String getScoreFile() {
		return scoreFile;
	}
	
	public void retrieveScores(){
		scoreFile = FileMgr.loadFile("hiscore.scr");
		if (scoreFile != ""){		
			for (int i = 0 , indx1 = 0 , indx2 = 0 ; i < 10 ; i++){
				indx2 = scoreFile.indexOf('.', indx1);
				names[i]= scoreFile.substring(indx1, indx2);
				indx1 = indx2+1;
				indx2 = scoreFile.indexOf('.', indx1);
				scores[i] = Integer.parseInt(scoreFile.substring(indx1, indx2));
				indx1 = indx2+1;
			}	
		}
		else{
			for (int i = 0 ; i < 10 ; i++){
				names[i]= "AAAA";
				scores[i] = (10 - i) * 10000;
			}	
			saveScores();
		}
		
		
	}
	
	public void saveScores(){
		scoreFile = "";
		for(int i = 0 ; i<10 ; i++)
			scoreFile += names[i] + "." + scores[i] + ".";
		FileMgr.saveFile("hiscore.scr",scoreFile);
	}
	
	public boolean isScoreHighEnough(int x){
		for (int i = 0; i < scores.length; i++) {
			if (x > scores[i])
				return true;
		}
		return false;
	}
	
	public void addScore(int x, String name){
		if (isScoreHighEnough(x)){
			names[9]=name;
			scores[9]=x;
			sortScores();
			saveScores();
		}
	}
	
	private void sortScores(){
        int temp;
        String temp2;
        for(int i=0; i < scores.length-1; i++){
 
            for(int j=1; j < scores.length-i; j++){
                if(scores[j-1] < scores[j]){
                    temp=scores[j-1];
                    temp2=names[j-1];
                    scores[j-1] = scores[j];
                    names[j-1] = names[j];
                    scores[j] = temp;
                    names[j] = temp2;
                }
            }
        }
    }
	
	
}
